package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.interestRelated.HiseCommQryResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.ComuserBusinacctQryForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.interestRelated.HiseCommQryForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.interestRelated.HiseCommQryBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.RecommendComuserType;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.RecommendRrderType;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.UserType;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.CombineBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.IndiviDemandBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.back.CombineRecommendQryData;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.back.ComuserRecommendQryData;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.back.HomeCombRecQryList;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.back.HomeComuserRecQryList;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.HomeCombRecForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.HomeCuserRecForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.SignapplyForm;
import com.cloudbroker.bcs.platform.ltb.middle.entity.RecommendRule;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.service.RecommendRuleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.cloudbroker.bcs.common.util.VOUtil.setSuccessResult;

/**
 * Created by fangyf18371 on 2016/12/10.
 */
@Service
public class IndiviDemandBizServiceImpl implements IndiviDemandBizService{
    @Resource
    private LedT2Service ledT2Service;
    @Resource
    private RecommendRuleService recommendRuleService;//推荐规则服务

    //调用后台接口
    @Resource
    private LightinvestingService lightinvestingService;

//    @Resource
//    private TradBackRoundService tradBackRoundService;//连接后台服务

    @Resource
    private CombineBizService combineBizService;

    /**
     * 首页组合推荐
     * @param param
     * @return
     */
    @Override
    public HomeCombRecQryList home_comb_rec(HomeCombRecForm param) {
        RecommendedCombForm recommendedCombForm=new RecommendedCombForm();//后台组合推荐请求Vo
        RecommendRule recommendRule = new RecommendRule ();//规则po
        String reorderType=recommendRule.getRecommend_order_type();//获取规则表中推荐方式
        if((RecommendRrderType.EARNINGS.getVal()).equals(reorderType ) || (RecommendRrderType.SENTIMENT.getVal()).equals(reorderType) ){//运营管理端设置按收益或者人气排序
            CombRankForm combRankForm=new CombRankForm();//后台组合排名请求vo
            combRankForm.setComorder_type(recommendRule.getRecommend_order_type());//设置组合排序类别
            CombRankQryBackVo combRankQryVo=lightinvestingService.func_comb_rank(combRankForm);//后台组合排名请求结果集
            List<CombRankResult> combRank=combRankQryVo.getData_list();//后台组合排名结果
            List<CombineRecommendQryData> combineRecommendQryDatas=new ArrayList<>();//中台组合推荐结果集

            if(!"0".equals(combRankQryVo.getError_no())){
                return VOUtil.genErrorResult(combRankQryVo.getError_no(),combRankQryVo.getError_info(),HomeCombRecQryList.class);
            }
            if(null==combRankQryVo){
                return setSuccessResult(new HomeCombRecQryList());
            }
            for (CombRankResult tmp : combRank) {//后台组合排名接口结果集轮循赋值给组合推荐
                CombineRecommendQryData combineRecommendQryData=new CombineRecommendQryData();//中台组合推荐实体
                combineRecommendQryData.setBackground_info(tmp.getBackground_info());
                combineRecommendQryData.setPosition_str(tmp.getPosition_str());
                combineRecommendQryData.setBegin_date(tmp.getBegin_date());
                combineRecommendQryData.setCollect_num(tmp.getCollect_num());
                combineRecommendQryData.setComb_fare(tmp.getComb_fare());
                combineRecommendQryData.setComb_fare_org(tmp.getComb_fare_org());
                combineRecommendQryData.setCombi_code(tmp.getCombi_code());
                combineRecommendQryData.setCombi_name(tmp.getCombi_name());
                combineRecommendQryData.setCombi_status(tmp.getCombi_status());
                combineRecommendQryData.setCombine_kind(tmp.getCombine_kind());
                combineRecommendQryData.setInvest_style(tmp.getInvest_style());
                combineRecommendQryData.setIncome_ratio(tmp.getIncome_ratio());
                combineRecommendQryData.setFocus_num(tmp.getFocus_num());
                combineRecommendQryData.setSummary(tmp.getSummary());
                combineRecommendQryData.setCreate_date(tmp.getCreate_date());
                combineRecommendQryData.setEnd_date(tmp.getEnd_date());
                combineRecommendQryData.setComtag_str(tmp.getComtag_str());
                combineRecommendQryData.setFare_per_month(tmp.getFare_per_month()); //    fare_per_month	N19.2	月费用
                combineRecommendQryData.setFare_per_quarter(tmp.getFare_per_quarter());//   fare_per_quarter	N19.2	季度费用
                combineRecommendQryData.setFare_per_halfyear(tmp.getFare_per_halfyear());//   fare_per_halfyear	N19.2	半年费用
                combineRecommendQryData.setFare_per_year(tmp.getFare_per_year());//  fare_per_year	N19.2	年费用
                combineRecommendQryData.setFare_per_month_org(tmp.getFare_per_month_org());//  fare_per_month_org	N19.2	原月费用
                combineRecommendQryData.setFare_per_quarter_org(tmp.getFare_per_quarter_org());//  fare_per_quarter_org	N19.2	原季度费用
                combineRecommendQryData.setFare_per_halfyear_org(tmp.getFare_per_halfyear_org());//  fare_per_halfyear_org	N19.2	原半年费用
                combineRecommendQryData.setFare_per_year_org(tmp.getFare_per_year_org());//  fare_per_year_org	N19.2	原年费用
                combineRecommendQryData.setMax_rate(tmp.getMax_rate());// max_rate	N9.8	最高比例
                combineRecommendQryData.setStock_code(tmp.getStock_code());// stock_code	C6	证券代码
                combineRecommendQryData.setStock_name(tmp.getStock_name());// stock_name	C32	证券名称
                combineRecommendQryData.setCombi_feature(tmp.getCombi_feature());// combi_feature	C2000	组合特点
                combineRecommendQryDatas.add(combineRecommendQryData);
            }
            HomeCombRecQryList homeCombRecQryList=new HomeCombRecQryList();//中台组合推荐结果集
            homeCombRecQryList.setData_list(combineRecommendQryDatas);
            return  setSuccessResult(homeCombRecQryList);
        }
        recommendedCombForm.setOp_branch_no(param.getOp_branch_no());
        recommendedCombForm.setOp_entrust_way(param.getOp_entrust_way());
        recommendedCombForm.setOp_station(param.getOp_station());
        recommendedCombForm.setBranch_no(param.getBranch_no());
        recommendedCombForm.setPassword(param.getPassword());
        recommendedCombForm.setPassword_type(param.getPassword_type());
        recommendedCombForm.setUser_token(param.getUser_token());
        recommendedCombForm.setSendercomp_id(param.getSendercomp_id());
        recommendedCombForm.setRecommend_flag(param.getRecommend_flag());
        recommendedCombForm.setRequest_num(param.getRequest_num());
        recommendedCombForm.setPosition_str(param.getPosition_str());
        RecommendedCombQryBackVo recommendedCombQryBackVo=ledT2Service.func_comb_recommend(recommendedCombForm);
        List<RecommendedCombResult> recommendedCombResults=recommendedCombQryBackVo.getData_list();//后台组合推荐接口集合
        List<CombineRecommendQryData> list = JSON.parseObject(JSON.toJSONString(recommendedCombResults),new TypeReference<List<CombineRecommendQryData>>(){});
        if(!"0".equals(recommendedCombQryBackVo.getError_no())){
            return VOUtil.genErrorResult(recommendedCombQryBackVo.getError_no(),recommendedCombQryBackVo.getError_info(),HomeCombRecQryList.class);
        }
        if(null==recommendedCombResults){
            return setSuccessResult(new HomeCombRecQryList());
        }

        HomeCombRecQryList homeCombRecQryList=new HomeCombRecQryList();//中台组合推荐结果集
        homeCombRecQryList.setData_list(list);
        return setSuccessResult(homeCombRecQryList);
    }

    /**
     * 首页达人推荐
     * @param param
     * @return
     */
    @Override
    public HomeComuserRecQryList home_comuser_rec(HomeCuserRecForm param) {
        RecommendInterestForm recommendInterestForm=new RecommendInterestForm();//后台达人推荐请求vo
        RecommendRule recommendRule = new RecommendRule ();
        String reorderType=recommendRule.getRecommend_order_type();//获取规则表中推荐方式
        if((RecommendComuserType.TOTALREVENUE.getVal()).equals(reorderType ) || (RecommendComuserType.COLLECTSENTIMENT.getVal()).equals(reorderType) ){//按人气或收益排序
            InterestRankForm interestRankForm=new InterestRankForm();//后台达人排名请求vo
            interestRankForm.setComorder_type(recommendRule.getRecommend_order_type());//达人排名排序类别
            InterestRankQryBackVo interestRankQryBackVo=lightinvestingService.func_interest_rank_query(interestRankForm);//后台达人排名结果集
            List<InterestRankResult> interestRankResults=interestRankQryBackVo.getData_list();//后台达人排名结果
            List<ComuserRecommendQryData> comuserRecommendQryDatas=new ArrayList<>();//中台达人推荐结果集
            if(!"0".equals(interestRankQryBackVo.getError_no())){
                return VOUtil.genErrorResult(interestRankQryBackVo.getError_no(),interestRankQryBackVo.getError_info(),HomeComuserRecQryList.class);
            }
            if(null==interestRankQryBackVo){
                return VOUtil.setSuccessResult(new HomeComuserRecQryList());
            }
            for(InterestRankResult tmp:interestRankResults){
                ComuserRecommendQryData comuserRecommendQryData=new ComuserRecommendQryData();//达人推荐结果实体
                comuserRecommendQryData.setUser_id(tmp.getUser_id());
                comuserRecommendQryData.setAlias_name(tmp.getAlias_name());
                comuserRecommendQryData.setUser_type(tmp.getUser_type());
                comuserRecommendQryData.setIncome_ratio(tmp.getIncome_ratio());
                comuserRecommendQryData.setCollect_num(tmp.getCollect_num());
                comuserRecommendQryData.setToday_income_ratio(tmp.getIncome_ratio());
                comuserRecommendQryData.setSuccess_num(tmp.getSuccess_num());
                comuserRecommendQryData.setFail_num(tmp.getFail_num());
                comuserRecommendQryData.setClient_branch_no(tmp.getClient_branch_no());
                comuserRecommendQryData.setBranch_name(tmp.getBranch_name());
                comuserRecommendQryData.setAdviser_type(tmp.getAdviser_type());
                comuserRecommendQryData.setPosition_str(tmp.getPosition_str());
                comuserRecommendQryData.setCombi_code(tmp.getCombi_code());
                comuserRecommendQryData.setCombi_name(tmp.getCombi_name());
                comuserRecommendQryData.setBackground_info(tmp.getBackground_info());
                comuserRecommendQryData.setEn_cominvest_style(tmp.getEn_cominvest_style()); // en_cominvest_style
                comuserRecommendQryData.setInvest_strategy(tmp.getInvest_strategy());//        invest_strategy
                comuserRecommendQryData.setInvest_strategy_oview(tmp.getInvest_strategy_oview());
                comuserRecommendQryDatas.add(comuserRecommendQryData);
            }
            HomeComuserRecQryList homeComuserRecQryList=new HomeComuserRecQryList();//中台达人推荐
            homeComuserRecQryList.setData_list(comuserRecommendQryDatas);
            return setSuccessResult(homeComuserRecQryList);
        }
        recommendInterestForm.setOp_branch_no(param.getOp_branch_no());
        recommendInterestForm.setOp_entrust_way(param.getOp_entrust_way());
        recommendInterestForm.setOp_station(param.getOp_station());
        recommendInterestForm.setBranch_no(param.getBranch_no());
        recommendInterestForm.setPassword(param.getPassword());
        recommendInterestForm.setPassword_type(param.getPassword_type());
        recommendInterestForm.setUser_token(param.getUser_token());
        recommendInterestForm.setSendercomp_id(param.getSendercomp_id());
        recommendInterestForm.setRecommend_flag(param.getRecommend_flag());
        recommendInterestForm.setRequest_num(param.getRequest_num());
        recommendInterestForm.setPosition_str(param.getPosition_str());
        RecommendInterestQryBackVo recommendInterestQryBackVo=ledT2Service.func_recommend_interest_query(recommendInterestForm);
        List<RecommendInterestResult> recommendedCombResults=recommendInterestQryBackVo.getData_list();//后台达人推荐接口集合
        List<ComuserRecommendQryData> list = JSON.parseObject(JSON.toJSONString(recommendedCombResults),new TypeReference<List<ComuserRecommendQryData>>(){});
        if(!"0".equals(recommendInterestQryBackVo.getError_no())){
            return VOUtil.genErrorResult(recommendInterestQryBackVo.getError_no(),recommendInterestQryBackVo.getError_info(),HomeComuserRecQryList.class);
        }
        if(null==recommendInterestQryBackVo){
            return setSuccessResult(new HomeComuserRecQryList());
        }
        HomeComuserRecQryList homeComuserRecQryList=new HomeComuserRecQryList();//中台达人推荐
        homeComuserRecQryList.setData_list(list);

        return setSuccessResult(homeComuserRecQryList);
    }


    /**
     * 达人签约申请查询
     * @param param
     * @return
     */
    @Override
    public SignapplyQryBackVo func_extcomacct_signapply_qry(SignapplyForm param) {
        SignapplyQryForm signapplyQryForm=new SignapplyQryForm();//达人签约申请查询
        signapplyQryForm.setOp_branch_no(param.getOp_branch_no());
        signapplyQryForm.setOp_station(param.getOp_station());
        signapplyQryForm.setOp_entrust_way(param.getOp_entrust_way());
        signapplyQryForm.setBranch_no(param.getBranch_no());
        signapplyQryForm.setPassword(param.getPassword());
        signapplyQryForm.setPassword_type(param.getPassword_type());
        signapplyQryForm.setUser_token(param.getUser_token());
        signapplyQryForm.setSendercomp_id(param.getSendercomp_id());
//        if(param.getAdviser_id() != null){
//            signapplyQryForm.setAdviser_id(String.valueOf(param.getAdviser_id()));
//        }
        if(param.getUser()!=null && param.getUser().getUser_type().equals(String.valueOf(UserType.LEADER.getVal()))){//投顾
            signapplyQryForm.setAdviser_id(String.valueOf(param.getUser().getUser_id()));//如果是投顾，从user_token取uesr_id赋值
        }
        if(param.getUser()!=null && param.getUser().getUser_type().equals(String.valueOf(UserType.CUSTOMER.getVal()))){//粉丝
            signapplyQryForm.setAdviser_id(param.getAdviser_id());//是粉丝，那么需要传adviser_id
            signapplyQryForm.setUser_id(String.valueOf(param.getUser().getUser_id()));//粉丝端调用需传粉丝user_id
        }
        signapplyQryForm.setStart_date(param.getStart_date());//	C18	投顾编号
        signapplyQryForm.setEnd_date(param.getEnd_date());
        signapplyQryForm.setVerify_status(param.getVerify_status());
        signapplyQryForm.setPosition_str(param.getPosition_str());
        signapplyQryForm.setRequest_num(param.getRequest_num());

        SignapplyQryBackVo signapplyQryBackVo=lightinvestingService.func_extcomacct_signapply_qry(signapplyQryForm);//达人签约申请查询
        List<SignapplyQryResult> signapplyQryResults=signapplyQryBackVo.getData_list();
        if (!signapplyQryBackVo.getError_no().equals("0")) {
            return VOUtil.genBGErrorResult(signapplyQryBackVo.getError_no(), signapplyQryBackVo.getError_info(), SignapplyQryBackVo.class);
        }
        if (null == signapplyQryResults){
            //// TODO: 2017/1/16

            return VOUtil.setSuccessResult(new SignapplyQryBackVo());
//            return VOUtil.genBGErrorResult(" ", " ", SignapplyQryBackVo.class);
        }

        String verifyStatus=param.getVerify_status();//审核状态 0未审核
        if("0".equals(verifyStatus)){//如果未审核
            ComuserBusinacctQryForm comuserBusinacctQryForm=new ComuserBusinacctQryForm();//后台账户绑定关系查询
            HiseCommQryForm hiseCommQryForm=new HiseCommQryForm();//历史证券委托查询
            Double tradVolume=0D;//交易量
            Long tradNumber=0L;//交易次数
            for(SignapplyQryResult tnp:signapplyQryResults){
                comuserBusinacctQryForm.setOp_branch_no(param.getOp_branch_no());
                comuserBusinacctQryForm.setOp_entrust_way(param.getOp_entrust_way());
                comuserBusinacctQryForm.setOp_station(param.getOp_station());
                comuserBusinacctQryForm.setBranch_no(param.getBranch_no());
                comuserBusinacctQryForm.setPassword(param.getPassword());
                comuserBusinacctQryForm.setPassword_type(param.getPassword_type());
                comuserBusinacctQryForm.setUser_token(param.getUser_token());
                comuserBusinacctQryForm.setSendercomp_id(param.getSendercomp_id());
                comuserBusinacctQryForm.setUser_id(tnp.getUser_id());//粉丝
                comuserBusinacctQryForm.setIs_adviser_search("1");
                comuserBusinacctQryForm.setCompany_id(param.getCompany_id());

                ComuserBusinacctQryBackVo comuserBusinacctQryBackVo=lightinvestingService.func_comuser_businacct_qry(comuserBusinacctQryForm);//查询账户绑定关系
                List<ComuserBusinacctQryResult> comuserBusinacctQryResults=comuserBusinacctQryBackVo.getData_list();

                if (!comuserBusinacctQryBackVo.getError_no().equals("0")){
                    return VOUtil.genBGErrorResult(comuserBusinacctQryBackVo.getError_no(), comuserBusinacctQryBackVo.getError_info(), SignapplyQryBackVo.class);
                }
                if (null == comuserBusinacctQryResults){
                    //// TODO: 2017/1/16
                    continue;
//                    return VOUtil.setSuccessResult(signapplyQryBackVo);
                }

                ComuserBusinacctQryResult comuserBusinacctQryResult=comuserBusinacctQryResults.get(0);//取第一条
                if (null == comuserBusinacctQryResult){
                    continue;
                }
                hiseCommQryForm.setOp_branch_no(param.getOp_branch_no());
                hiseCommQryForm.setOp_entrust_way(param.getOp_entrust_way());
                hiseCommQryForm.setOp_station(param.getOp_station());
                hiseCommQryForm.setBranch_no(param.getBranch_no());
                hiseCommQryForm.setClient_id(comuserBusinacctQryResult.getClient_id());
                hiseCommQryForm.setFund_account(comuserBusinacctQryResult.getBusin_account());
                hiseCommQryForm.setPassword(param.getPassword());
                hiseCommQryForm.setPassword_type(param.getPassword_type());
                hiseCommQryForm.setUser_token(param.getUser_token());
                if (param.getUser() != null) {
                    hiseCommQryForm.setSendercomp_id(String.valueOf(param.getUser().getSendercomp_id()));
                    hiseCommQryForm.setCompany_id(String.valueOf(param.getUser().getCompany_id()));
                }
                hiseCommQryForm.setStart_date(param.getStart_date());
                hiseCommQryForm.setEnd_date(param.getEnd_date());
                hiseCommQryForm.setPosition_str(param.getPosition_str());
                hiseCommQryForm.setRequest_num(param.getRequest_num());

                HiseCommQryBackVo hiseCommQryBackVo=lightinvestingService.func_his_securities_commission_qry(hiseCommQryForm);//历史证券委托查询
                List<HiseCommQryResult> hiseCommQryResults=hiseCommQryBackVo.getData_list();
                if (!hiseCommQryBackVo.getError_no().equals("0")){
                    return VOUtil.genBGErrorResult(hiseCommQryBackVo.getError_no(), hiseCommQryBackVo.getError_info(), SignapplyQryBackVo.class);
                }
                if (null == hiseCommQryResults){
                    //// TODO: 2017/1/16
                    continue;
//                    return  setSuccessResult(signapplyQryBackVo);
                }


                for(HiseCommQryResult tup:hiseCommQryResults){
                    String entrustStatus=tup.getEntrust_status();//委托状态
                    if("4".equals(entrustStatus) || "5".equals(entrustStatus) ||"7".equals(entrustStatus) || "8".equals(entrustStatus)){
                        for(int i=0;i<=hiseCommQryResults.size();i++){
                            tradVolume+=tup.getBusiness_amount();
                        }
                        tradNumber=(long)hiseCommQryResults.size();
                    }

                    for(SignapplyQryResult k:signapplyQryResults){
                        SignapplyQryResult signapplyQryResult=new SignapplyQryResult();
                        signapplyQryResult.setApply_date(k.getApply_date());
                        signapplyQryResult.setApply_no(k.getApply_no());
                        signapplyQryResult.setVerify_status(k.getVerify_status());
                        signapplyQryResult.setPosition_str(k.getPosition_str());
                        signapplyQryResult.setSendercomp_id(k.getSendercomp_id());
                        signapplyQryResult.setDraw_ratio(k.getDraw_ratio());
                        signapplyQryResult.setCom_order_type(k.getCom_order_type());
                        signapplyQryResult.setPay_mode(k.getPay_mode());
                        signapplyQryResult.setFare_status(k.getFare_status());
                        signapplyQryResult.setBegin_date(k.getBegin_date());
                        signapplyQryResult.setEnd_date(k.getEnd_date());
                        signapplyQryResult.setAdviser_id(k.getAdviser_id());
                        signapplyQryResult.setUser_id(k.getUser_id());
                        signapplyQryResult.setAlias_name(k.getAlias_name());
                        signapplyQryResult.setIncome_ratio(k.getIncome_ratio());
                        signapplyQryResult.setComfare_mode(k.getComfare_mode());
                        signapplyQryResult.setTrad_volume(tradVolume);
                        signapplyQryResult.setTrad_number(tradNumber);
                        signapplyQryResults.add(signapplyQryResult);
                    }

                }

            }

        }
        SignapplyQryBackVo backVo=new SignapplyQryBackVo();
        backVo.setData_list(signapplyQryResults);
//        signapplyQryBackVo.setData_list(signapplyQryResults);
        return setSuccessResult(backVo);
    }


}
